import { join } from "path"
import { paramCase } from "param-case";
import { parseImportModule, codeIncludesLibraryName, stylePathHandler, isFunction, isBool } from "./utils";

const swcImportLoader = function (content: string) {
    const options = this.getOptions();
    if (options.rspackExperiments && options.rspackExperiments.import) {
        const libList = options.rspackExperiments.import || [];
        const ignoreStylePathNotFound = options.rspackExperiments.ignoreStylePathNotFound || true;
        const hasCodeIncludesLibraryName = codeIncludesLibraryName(content, libList);
        if (hasCodeIncludesLibraryName) {
            const { importMaps } = parseImportModule(content, libList);
            let importStr = ''
            libList.forEach(({ libraryName, libraryDirectory, style, camel2DashComponentName = true }) => {
                if (importMaps[libraryName]) {
                    importMaps[libraryName].forEach((item: string) => {
                        if (camel2DashComponentName) {
                            item = paramCase(item)
                        }

                        let stylePath: string;
                        let prefixPath = libraryName;

                        if (libraryDirectory) {
                            prefixPath = join(libraryName, libraryDirectory)
                        }

                        if (isFunction(style)) {
                            stylePath = style(join(prefixPath, item), item)
                        } else if (isBool(style)) {
                            stylePath = join(prefixPath, item, 'style')
                        } else if (style == 'css') {
                            stylePath = join(prefixPath, item, 'style', 'css')
                        } else {
                            stylePath = join(prefixPath, item)
                        }

                        const styleImportString = stylePathHandler(stylePath, ignoreStylePathNotFound)

                        if (styleImportString) {
                            importStr += styleImportString + '\n'
                        }
                    })
                }
            });
            return importStr + content
        }
    }
    return content;
}

export default swcImportLoader